﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using LitJson;

public static class JsonHelper
{
    public static void Foreach(string json, Type type, Action<Type, string, JsonData> action,Action complete=null)
    {
        ForeachJson(JsonMapper.ToObject(json), type, action, string.Empty);
        if(complete!=null)
        complete.Invoke();
    }

    static void ForeachJson(JsonData data, Type type, Action<Type, string, JsonData> action, string dataKey)
    {
        action(type, dataKey, data);
        switch (data.GetJsonType())
        {
            case JsonType.Object:
                foreach(KeyValuePair<string,JsonData> pair in data)
                {
                    var field = type.GetField(pair.Key, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                    if (field == null)
                        continue;
                    ForeachJson(pair.Value, field.FieldType, action, pair.Key);

                }
                break;
            case JsonType.Array:
                if(type.IsArray)
                {
                    type = type.GetElementType();
                }
                if(typeof(IList).IsAssignableFrom(type))
                {
                    type = type.GetProperty("Item").PropertyType;
                }
                foreach (JsonData item in data)
                {
                    ForeachJson(item, type, action, dataKey);
                }
                break;
        }
    }
}